package tests.main_tests;

import static org.junit.Assert.*;

import org.junit.Test;

import application.main.Application;
import application.main.QuitHandler;

import java.io.File;

public class Application_test {

	private boolean quitHandlerFail1;
	private boolean quitHandlerFail2;
	
	@Test
	public void resourceDirectoryTest() {
		
		if(!(new File(Application.getResourceDirectoryPath()).isDirectory())) fail("Path name does not point at an existing directory in the file system.");
	}
	
	@Test
	public void quitHandlerTest() {
		
		QuitHandler quitHandler = new QuitHandler() {
			
			public boolean requestQuit(){
				
				quitHandlerFail1 = false;
				
				return false;
			}
		};
		
		// Test that we may add and remove an quitHandler
		quitHandlerFail1 = true;
		Application.registerQuitHandler(quitHandler);
		Application.quit(); // quitHandler should make quitHandlerFail1 = false
		if(quitHandlerFail1) fail();
		
		quitHandlerFail1 = true;
		Application.unregisterQuitHandler(quitHandler);
		Application.quit();
		if(!quitHandlerFail1) fail(); // If quitHandlerFail1 is false, the quitHandler has not been removed
		
		// Test that we may add and remove multiple quitHandlers
		QuitHandler quitHandler2 = new QuitHandler() {
			
			public boolean requestQuit(){
				
				quitHandlerFail2 = false;
				
				return false;
			}
		};
		
		// Add 2 quitHandlers and test
		quitHandlerFail1 = true;
		quitHandlerFail2 = true;
		Application.registerQuitHandler(quitHandler);
		Application.registerQuitHandler(quitHandler2);
		Application.quit();
		if(quitHandlerFail1 || quitHandlerFail2) fail();
		
		// Remove one - quitHandler must fail and quitHandler2 succeed or both have been removed
		quitHandlerFail1 = true;
		quitHandlerFail2 = true;
		Application.unregisterQuitHandler(quitHandler);
		Application.quit();
		if(!quitHandlerFail1 || quitHandlerFail2) fail();
		
		// Remove the remaining quitHandler
		quitHandlerFail1 = true;
		quitHandlerFail2 = true;
		Application.unregisterQuitHandler(quitHandler2);
		Application.quit();
		if(!quitHandlerFail1 || !quitHandlerFail2) fail();
		
		// Test that you cannot add null quitHandlers
		boolean fail = true;
		try{ Application.registerQuitHandler(null); }
		catch(NullPointerException e){fail = false;}
		if(fail) fail();
		
		// We already know, that quitHandlers successfully may stop the quit process
		// If not we would not have come this far.
		// Test that they can approve it as well and make the application quit!
		
		Application.registerQuitHandler(new QuitHandler(){
			
			public boolean requestQuit(){
				
				return true;
			}
		});
		Application.quit();
		fail("The application did not quit when told to!");
	}
}
